<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="query.beanName"
          placeholder="bean名称"
          class="handle-input mr10"
          clearable
          @keyup.native.enter="handleSearch()"
        ></el-input>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button
          type="primary"
          @click="handleAdd"
          v-if="jsPermissions.includes('sys:schedule:save')"
          >新增</el-button
        >
        <el-button
          type="danger"
          class="handle-del"
          @click="delAllSelection"
          v-if="jsPermissions.includes('sys:schedule:delete')"
          >删除</el-button
        >
        <el-button
          type="danger"
          @click="handleAllPause"
          v-if="jsPermissions.includes('sys:schedule:update')"
          >暂停</el-button
        >
        <el-button
          type="danger"
          @click="handleAllResume"
          v-if="jsPermissions.includes('sys:schedule:update')"
          >恢复</el-button
        >
        <el-button
          type="danger"
          @click="handleAllRun"
          v-if="jsPermissions.includes('sys:schedule:update')"
          >执行</el-button
        >
        <el-button type="success" @click="handleScheduleLog"
          >日志列表</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="beanName"
          label="bean名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="params"
          label="参数"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="cronExpression"
          label="cron表达式"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" sortable align="center" prop="status">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.status === '正常'
                  ? 'success'
                  : scope.row.status === '暂停'
                  ? 'danger'
                  : ''
              "
              >{{ scope.row.status }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="jsPermissions.includes('sys:schedule:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="handlePause(scope.$index, scope.row)"
              v-if="jsPermissions.includes('sys:schedule:update')"
              >暂停</el-button
            >
            <el-button
              type="text"
              @click="handleResuem(scope.$index, scope.row)"
              v-if="jsPermissions.includes('sys:schedule:update')"
              >恢复</el-button
            >
            <el-button
              type="text"
              @click="handleRun(scope.$index, scope.row)"
              v-if="jsPermissions.includes('sys:schedule:update')"
              >执行</el-button
            >
            <el-button
              type="text"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="jsPermissions.includes('sys:schedule:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="auto"
        :rules="rules"
      >
        <el-form-item label="bean名称" prop="beanName">
          <el-input v-model="editForm.beanName" clearable></el-input>
        </el-form-item>
        <el-form-item label="参数">
          <el-input v-model="editForm.params" clearable></el-input>
        </el-form-item>
        <el-form-item label="cron表达式" prop="cronExpression">
          <el-input v-model="editForm.cronExpression" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 日志列表弹出框 -->
    <el-dialog title="日志列表" :visible.sync="scheduleLogVisible" width="80%">
      <el-form ref="scheduleLogForm" :model="scheduleLogForm">
        <el-form-item>
          <el-input
            v-model="query.jobId"
            class="handle-input mr11"
            placeholder="任务ID"
            clearable
          ></el-input>
          <el-button type="primary" plain @click="handleSLSearch"
            >查询</el-button
          >
        </el-form-item>

        <div>
          <div class="container">
            <el-table
              :data="slTableData"
              border
              class="table"
              ref="multipleTable"
              header-cell-class-name="table-header"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                prop="jobId"
                :show-overflow-tooltip="true"
                label="任务ID"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="beanName"
                label="bean名称"
              ></el-table-column>
              <el-table-column prop="params" label="参数"></el-table-column>

              <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                  <el-tag
                    :type="
                      scope.row.status === '成功'
                        ? 'success'
                        : scope.row.status === '失败'
                        ? 'danger'
                        : ''
                    "
                    >{{ scope.row.status }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column
                prop="consumeTime"
                label="耗时(单位: 毫秒)"
              ></el-table-column>

              <el-table-column
                prop="runDate"
                label="执行时间"
              ></el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                background
                layout="total,sizes, prev, pager, next, jumper"
                :page-sizes="[5, 10, 20, 30]"
                @size-change="handleSizeChange"
                :current-page="query.pageIndex"
                :page-size="query.pageSize"
                :total="pageTotal"
                @current-change="handlePageChange"
              ></el-pagination>
            </div>
          </div>
        </div>
      </el-form>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="50%">
      <el-form ref="form" :model="addForm" label-width="auto" :rules="rules">
        <el-form-item label="bean名称" prop="beanName">
          <el-input v-model="addForm.beanName" clearable></el-input>
        </el-form-item>
        <el-form-item label="参数">
          <el-input v-model="addForm.params" clearable></el-input>
        </el-form-item>
        <el-form-item label="cron表达式" prop="cronExpression">
          <el-input v-model="addForm.cronExpression" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addForm.remark" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { jobScheduleMixin } from "common/js/systemSettings";
import util from "utils/util";
import { mapGetters } from "vuex";
export default {
  name: "jobschedule",
  // mixins: [jobScheduleMixin],
  data() {
    return {
      jsPermissions: [],
      query: {
        order: "",
        orderField: "",
        pageIndex: 1,
        pageSize: 20,
        beanName: "",
        jobId: "",
      },
      tableData: [
        {
          id: "",
          beanName: "",
          params: "",
          cronExpression: "",
          status: 0,
          remark: "",
          createDate: null,
        },
      ],
      // 日志列表
      slTableData: [
        {
          id: "",
          jobId: "",
          beanName: "",
          params: "",
          status: 0,
          consumeTime: "",
          runDate: "",
        },
      ],
      multipleSelection: [],
      delList: [],
      // ...commonVisible,
      editVisible: false,
      addVisible: false,
      scheduleLogVisible: false,
      pageTotal: 0,
      rules: {
        beanName: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        cronExpression: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
      },
      addForm: {
        beanName: "",
        params: "",
        cronExpression: "",
        status: 0,
        remark: "",
      },
      editForm: {
        id: "",
        remark: "",
        createDate: "",
        beanName: "",
        params: "",
        cronExpression: "",
        status: "",
      },
      scheduleLogForm: {},
      idx: -1,
      ids: [],
      dddown: true, // 防止重复点击
    };
  },
  methods: {
    // 获取数据
    getJSData({
      order = this.query.order,
      orderField = this.query.orderField,
      page = this.query.pageIndex,
      limit = this.query.pageSize,
      beanName = this.query.beanName,
      _t = Date.now(),
    }) {
      this.$axios
        .get("/sys/schedule/page", {
          params: {
            order,
            orderField,
            page,
            limit,
            beanName,
            _t,
          },
        })
        .then(({ data: res }) => {
          // console.log(res);
          if (res.code !== 0) {
            return;
          }
          this.pageTotal = res.data.total || 0;
          this.tableData = res.data.list;
          this.tableData.map((item) => {
            item.status = item.status === 0 ? "暂停" : "正常";
          });
        })
        .catch(() => {});
    },
    // 表头排序
    sortChange({ column, prop, order }) {
      prop = prop === "createDate" ? "create_date" : prop;
      this.$set(this.query, "orderField", prop);
      if (order === "ascending") {
        this.$set(this.query, "order", order.substr(0, 3));
        this.getJSData({});
      } else if (order === "descending") {
        this.$set(this.query, "order", order.substr(0, 4));
        this.getJSData({});
      }
    },
    // 日志列表
    handleSLSearch({
      order = this.query.order,
      orderField = this.query.orderField,
      page = this.query.pageIndex,
      limit = this.query.pageSize,
      jobId = this.query.jobId,
      _t = Date.now(),
    }) {
      this.$axios
        .get("/sys/scheduleLog/page", {
          params: {
            order,
            orderField,
            page,
            limit,
            jobId,
            _t,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.pageTotal = res.data.total || 0;
          this.slTableData = res.data.list;
          this.slTableData.map((item) => {
            item.status = item.status === 0 ? "暂停" : "正常";
          });
        })
        .catch(() => {});
    },
    handleScheduleLog() {
      this.scheduleLogVisible = true;
      this.handleSLSearch({});
    },
    // 执行
    handleAllRun() {
      var idList = this.multipleSelection.map((item) => {
        return item.id;
      });
      if (idList.length === 0) {
        return this.$message.error("请选择执行项");
      }
      this.$confirm("确定要执行吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          // 得到成功提示
          this.$axios
            .put("/sys/schedule/run", idList)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return;
              }
              this.$message.success("操作成功");
              this.getJSData({});
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 恢复
    handleAllResume() {
      var idList = this.multipleSelection.map((item) => {
        return item.id;
      });
      if (idList.length === 0) {
        return this.$message.error("请选择恢复项");
      }
      this.$confirm("确定要恢复吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          // 得到成功提示
          this.$axios
            .put("/sys/schedule/resume", idList)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return;
              }
              this.$message.success("操作成功");
              this.getJSData({});
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 暂停
    handleAllPause() {
      var idList = this.multipleSelection.map((item) => {
        return item.id;
      });
      if (idList.length === 0) {
        return this.$message.error("请选择暂停项");
      }
      this.$confirm("确定要暂停吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          // 得到成功提示
          this.$axios
            .put("/sys/schedule/pause", idList)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return;
              }
              this.$message.success("操作成功");
              this.getJSData({});
            })
            .catch(() => {});
        })
        .catch(() => {});
    },

    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.getJSData({
        beanName: this.query.beanName,
      });
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.editVisible = true;

      this.$axios
        .get("/sys/schedule/" + row.id, {
          params: {
            _t: Date.now(),
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          // 初始化编辑表单
          this.editForm = res.data;
        })
        .catch(() => {});
    },
    // 保存编辑
    saveEdit() {
      // 得到成功提示
      this.$axios
        .put("/sys/schedule", {
          id: this.editForm.id,
          beanName: this.editForm.beanName,
          params: this.editForm.params,
          cronExpression: this.editForm.cronExpression,
          status: this.editForm.status,
          remark: this.editForm.remark,
          createDate: this.editForm.createDate,
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.editVisible = false;
          this.$message.success("操作成功");
          this.getJSData({});
        })
        .catch(() => {});
    },
    // 执行操作
    handleRun(index, row) {
      this.$confirm("确定要执行吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          // 得到成功提示
          this.$axios
            .put("/sys/schedule/run", [row.id])
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return;
              }
              this.$message.success("操作成功");
              this.getJSData({});
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 恢复操作
    handleResuem(index, row) {
      this.$confirm("确定要恢复吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          // 得到成功提示
          this.$axios
            .put("/sys/schedule/resume", [row.id])
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return;
              }
              this.$message.success("操作成功");
              this.getJSData({});
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 暂停操作
    handlePause(index, row) {
      this.$confirm("确定要暂停吗?", "提示", { type: "warning" })
        .then(() => {
          // 得到成功提示
          this.$axios
            .put("/sys/schedule/pause", [row.id])
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return;
              }
              this.$message.success("操作成功");
              this.getJSData({});
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.delete.call(this, "/sys/schedule", index, this.ids, this.getJSData);
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 保存新增
    saveAdd() {
      // 得到成功提示
      if (this.dddown) {
        this.dddown = false;
        setTimeout(() => {
          this.$axios
            .post("/sys/schedule", {
              beanName: this.addForm.beanName,
              params: this.addForm.params,
              cronExpression: this.addForm.cronExpression,
              remark: this.addForm.remark,
              status: this.addForm.status,
            })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return;
              }
              this.addVisible = false;
              this.$message.success("操作成功");
              this.addForm = {};
              this.getJSData({});
            })
            .catch(() => {});
        }, 500);
      }
    },
    // 新增
    handleAdd() {
      this.addVisible = true;
    },
    // 批量删除
    delAllSelection() {
      var ids = this.multipleSelection.map((item) => {
        return item.id;
      });
      util.delete.call(this, "/sys/schedule", "", ids, this.getJSData);
    },

    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getJSData({});
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getJSData({});
    },
  },
  created() {
    this.getJSData({});
    this.jsPermissions = this.permissions;
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/job-schedule") {
        this.jsPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.jsPermissions = newVal;
    },
  },
  // methods: {
  //   }
};
</script>

<style scoped>
@import url("../../common/css/index.css");
.mr10 {
  width: 195px;
}
.mr11 {
  width: 195px;
  margin-right: 10px;
  vertical-align: middle;
}
</style>
